package com.zyw.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSONArray;

public class BaseController   {

	protected HttpServletRequest request;
	protected HttpServletResponse response;
	protected HttpSession session;
	
	protected Object getRequestAttribute(String key) {
		return this.request.getAttribute(key) != null ? this.request
				.getAttribute(key) : null;
	}

	protected Object getRequestParameter(String key) {
		return this.request.getParameter(key) != null ? this.request
				.getParameter(key) : null;
	}

	protected String getRequestParameter(String key, String nullStr) {
		try {
			String r = this.request.getParameter(key) != null ? this.request
					.getParameter(key) : nullStr;
			return r;
		} catch (Exception e) {
			return nullStr;
		}
	}
	protected String getParaneterToString(String key) {
		try {
			String r = this.request.getParameter(key) != null ? this.request
					.getParameter(key) : null;
			return r;
		} catch (Exception e) {
			return null;
		}
	}

	protected Integer getRequestParameterForInt(String key) {
		return Integer.valueOf(getRequestParameter(key, "-1"));
	}

	protected Integer getRequestAttributeForInt(String key) {
		return Integer.valueOf(getRequestAttribute(key).toString());
	}

	protected String getRequestIp() {
		return getIpAddress(this.request);
	}

	public String getRequestIp(HttpServletRequest request) {
		return getIpAddress(request);
	}

	public void responseError(String errorInfo) {
		responseInfo("error:"+errorInfo);
	}

	public void responseSuccess() {
		responseInfo("success");
	}

	public static String getIpAddress(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if ((ip == null) || (ip.length() == 0)
				|| ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if ((ip == null) || (ip.length() == 0)
				|| ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if ((ip == null) || (ip.length() == 0)
				|| ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if ((ip == null) || (ip.length() == 0)
				|| ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if ((ip == null) || (ip.length() == 0)
				|| ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
	
	public HttpServletRequest getRequest() {
		return this.request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletResponse getResponse() {
		return this.response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	public HttpSession getSession() {
		return this.session;
	}

	public void setSession(HttpSession session) {
		this.session = session;
	}

	@ModelAttribute
	public void setReqAndRes(HttpServletRequest request,
			HttpServletResponse response, HttpSession session) {
		this.request = request;
		this.response = response;
		this.session = session;
	}

	public BaseController(HttpServletRequest request,
			HttpServletResponse response, HttpSession session) {
		this.request = request;
		this.response = response;
		this.session = session;
	}

	public BaseController() {
	}

	public void responseInfo(String info) {
		try {
			responseInfo(info, "UTF-8", null);
		} catch (Exception e) {
		}
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void responseJsonList(List list) {
		responseInfo(new JSONArray(list).toJSONString());
	}

	public void responseInfo(String info, String encoding) {
		responseInfo(info, encoding, "text/plain");
	}

	public void responseInfo(String info, String encoding, String contentType) {
		try {
			if (contentType == null) {
				contentType = "text/html";
			}
			this.response.setContentType(contentType);
			this.response.setCharacterEncoding(encoding);
			PrintWriter pw = this.response.getWriter();
			pw.write(info);
			pw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void sendResponse(String url) {
		try {
			getResponse().sendRedirect(url);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void forward(String url) {
		try {
			getRequest().getRequestDispatcher(url).forward(getRequest(),
					getResponse());
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public List<String> saveUploadFile(String cachePath) {
		return saveUploadFile(cachePath, null);
	}

	public List<String> saveUploadFile(String cachePath, FileNameIntf fn) {
		if ((!FileUtil.valiPathIsExists(cachePath).booleanValue())
				|| (!FileUtil.valiPathIsFolder(cachePath).booleanValue())) {
			FileUtil.createFolder(cachePath);
		}
		List<String> rNameList = new ArrayList<>();

		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				this.request.getSession().getServletContext());
		if (multipartResolver.isMultipart(this.request)) {
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) this.request;

			Iterator<String> iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				MultipartFile file = multiRequest.getFile(iter.next()
						.toString());
				if (file != null) {
					String path = "";
					if (fn != null) {
						path = fn.updataFileName(file.getOriginalFilename(),cachePath);
					}else{
						path=file.getOriginalFilename();
					}
					rNameList.add(path);
					try {
						file.transferTo(new File(path));
					} catch (IllegalStateException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return rNameList;
	}

	public void responseFile(String name, File file) {
		if (file.exists()) {
			this.response.setContentType("application/force-download");
			this.response.addHeader("Content-Disposition",
					"attachment;fileName=" + name);
			byte[] buffer = new byte[1024];
			FileInputStream fis = null;
			BufferedInputStream bis = null;
			try {
				fis = new FileInputStream(file);
				bis = new BufferedInputStream(fis);
				OutputStream os = this.response.getOutputStream();
				int i = bis.read(buffer);
				while (i != -1) {
					os.write(buffer, 0, i);
					i = bis.read(buffer);
				}
			} catch (Exception e) {
				e.printStackTrace();
				if (bis != null) {
					try {
						bis.close();
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
				if (fis != null) {
					try {
						fis.close();
					} catch (IOException e2) {
						e2.printStackTrace();
					}
				}
			} finally {
				if (bis != null) {
					try {
						bis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (fis != null) {
					try {
						fis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	public void responseJson(String jsonStr) {
		responseInfo(jsonStr);
	}
}
